package com.baidu.bas.security.config;

import com.baidu.bas.core.constant.EruptRestPath;
import com.baidu.bas.security.interceptor.LoginInterceptor;
import com.baidu.bas.upms.config.EruptUpmsConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * @author liyuepeng
 * @date 2018-12-20.
 */

@Configuration
public class MvcInterceptor implements WebMvcConfigurer {

    @Resource
    private LoginInterceptor loginInterceptor;

    @Resource
    private EruptSecurityProp eruptSecurityProp;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns(EruptRestPath.ERUPT_API + "/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        CorsRegistration registration = registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(168000);
        if(eruptSecurityProp.isAllowCredentials()){
            registration
                    .allowedOrigins(eruptSecurityProp.getAllowOrigins())
                    .allowCredentials(true);
        }else{
            registration
                    .allowedOriginPatterns("*")
                    .allowCredentials(false);
        }
    }

//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler(RestPath.ERUPT_ATTACHMENT + "/**")
//                .addResourceLocations("file:" + eruptProp.getUploadPath());
//    }
}
